<template>
  <div id="standardDiv">
    <Breadcrumb content="点巡检标准" />
    <div class="bodyContent">
      <Splitpanes>
        <!-- 左侧表格  -->
        <Pane size="40">
          <vxe-toolbar perfect>
            <template #buttons>
              <!-- <div class="smallToolTitle">供应商维护</div> -->
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findPollingStandardList" @keyup="keyupEnter" @search-click="findPollingStandardList()"></vxe-input>

              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="findPollingStandardList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addStandardDialog()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteBatchStandard"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="standardTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="standardList" :loading="tloading" @current-change="standardRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30"></vxe-column>
              <vxe-column field="standardCode" title="标准编号" width="50">
                <template #default="{ row }">
                  <span>{{ row.standardCode }}</span>
                </template>
              </vxe-column>
              <vxe-column field="standardName" title="标准名称" width="200">
                <template #default="{ row }">
                  <el-link type="primary" :underline="false" @click="editStandardDialog(row)">
                    <span>{{ row.standardName }}</span>
                  </el-link>
                </template>
              </vxe-column>
              <vxe-column field="standardType" title="巡检类型" width="100">
                <template #default="{ row }">
                  <span>{{ row.standardType }}</span>
                </template>
              </vxe-column>
              <vxe-column field="purpose" title="巡检目的" width="100">
                <template #default="{ row }">
                  <span>{{ row.purpose }}</span>
                </template>
              </vxe-column>

              <vxe-column field="remark" title="备注">
                <template #default="{ row }">
                  <span>{{ row.remark }}</span>
                </template>
              </vxe-column>
              <vxe-column field="seq" title="顺序" width="80">
                <template #default="{ row }">
                  <span>{{ row.seq }}</span>
                </template>
              </vxe-column>
            </vxe-table>
          </div>

          <el-dialog :title="titleStandard()" :show-close="false" v-model="showStandardDialog" append-to-body width="500px" :close-on-click-modal="false">
            <el-form ref="standardFormRef" :model="standardForm" :rules="standardFormRule" label-width="100px" class="form-input-m" inline-message>
              <el-row>
                <el-col :span="24">
                  <el-form-item prop="standardCode" label="巡检编号">
                    <el-input type="text" v-model="standardForm.standardCode" placeholder="请输入巡检编号" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="standardName" label="巡检名称">
                    <el-input type="text" v-model="standardForm.standardName" placeholder="请输入巡检名称" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="standardType" label="巡检类型">
                    <el-input type="text" v-model="standardForm.standardType" placeholder="请输入巡检类型" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="purpose" label="巡检目的">
                    <el-input type="textarea" v-model="standardForm.purpose" placeholder="请输入巡检目的"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="tool" label="工具">
                    <el-input type="textarea" v-model="standardForm.tool" placeholder="请输入工具"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="remark" label="备注">
                    <el-input type="textarea" v-model="standardForm.remark" placeholder="请输入备注"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="order" label="排序">
                    <el-input-number v-model="standardForm.seq" :min="1" :max="1000" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

            <div class="dialog-footer flex right justify-end">
              <el-button type="primary" @click="saveStandard('standardFormRef')">保存</el-button>
              <el-button @click="closeStandardDialog('standardFormRef')">取消</el-button>
            </div>
          </el-dialog>
        </Pane>
        <!-- 右侧表单 -->
        <Pane size="60">
          <el-tabs type="border-card" v-model="activeName">
            <el-tab-pane label="检查项目" name="first">
              <vxe-toolbar perfect>
                <template #buttons>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addProjectDialog()" :disabled="isEmpty(sltStandard.id)"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteBatchProject"></vxe-button>
                </template>
              </vxe-toolbar>

              <div class="tableBody">
                <vxe-table ref="projectTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :data="projectList" :loading="ploading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                  <vxe-column type="checkbox" width="30"></vxe-column>
                  <vxe-column field="projectCode" title="项目编号" width="80">
                    <template #default="{ row }">
                      <span>{{ row.projectCode }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="projectName" title="项目名称" >
                    <template #default="{ row }">
                      <el-link type="primary" :underline="false" @click="editProjectDialog(row)">
                        <span>{{ row.projectName }}</span>
                      </el-link>
                    </template>
                  </vxe-column>
                  <vxe-column field="projectType" title="记录类型" width="80">
                    <template #default="{ row }">
                      <span>{{ formatProjectType(typeList, row.projectType) }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="normalValue" title="正常值" width="80">
                    <template #default="{ row }">
                      <span>{{ row.normalValue }}</span>
                    </template>
                  </vxe-column>

                  <vxe-column field="exceptValue" title="异常值" width="100">
                    <template #default="{ row }">
                      <span>{{ row.exceptValue }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="defValue" title="默认值" width="100">
                    <template #default="{ row }">
                      <span>{{ row.defValue }}</span>
                    </template>
                  </vxe-column>

                  <vxe-column field="maxValue" title="上限" width="80">
                    <template #default="{ row }">
                      <span>{{ row.maxValue }}</span>
                    </template>
                  </vxe-column>

                  <vxe-column field="mixValue" title="下限" width="80">
                    <template #default="{ row }">
                      <span>{{ row.mixValue }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="range" title="参考范围" width="100">
                    <template #default="{ row }">
                      <span>{{ row.range }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="seq" title="顺序" width="50">
                    <template #default="{ row }">
                      <span>{{ row.seq }}</span>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>

              <el-dialog :title="titleProject()" :show-close="false" v-model="showProjectDialog" append-to-body width="700px" :close-on-click-modal="false">
                <el-form ref="projectFormRef" :model="projectForm" :rules="projectFormRule" label-width="80px" class="form-input-m" inline-message>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item prop="projectCode" label="项目编号">
                        <el-input type="text" v-model="projectForm.projectCode" placeholder="请输入项目编号" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item prop="projectName" label="项目名称">
                        <el-input type="text" v-model="projectForm.projectName" placeholder="请输入项目名称" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item prop="projectType" label="记录类型">

                        <vxe-select v-model="projectForm.projectType" placeholder="请选择记录类型" style="width: 100%;">
                          <vxe-option v-for="typeObj in typeList" :key="typeObj.code" :label="typeObj.name" :value="typeObj.code" />
                        </vxe-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item prop="defValue" label="默认值">
                        <el-input type="text" v-model="projectForm.defValue" placeholder="请输入默认值"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="projectForm.projectType == 'radio'||projectForm.projectType == 'check'">
                      <el-form-item prop="normalValue" label="正常值">
                        <el-input type="text" v-model="projectForm.normalValue" placeholder="请输入正常值"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="projectForm.projectType == 'radio'||projectForm.projectType == 'check'">
                      <el-form-item prop="exceptValue" label="异常值">
                        <el-input type="text" v-model="projectForm.exceptValue" placeholder="请输入异常值"></el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="12" v-if="projectForm.projectType == 'num'">
                      <el-form-item prop="maxValue" label="上限">
                        <el-input type="text" v-model="projectForm.maxValue" placeholder="请输入上限"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="projectForm.projectType == 'num'">
                      <el-form-item prop="mixValue" label="下限">
                        <el-input type="text" v-model="projectForm.mixValue" placeholder="请输入下限"></el-input>
                      </el-form-item>
                    </el-col>

                    <el-col :span="12">
                      <el-form-item prop="range" label="参考范围">
                        <el-input type="text" v-model="projectForm.range" placeholder="请输入参考范围"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item prop="order" label="排序">
                        <el-input-number v-model="projectForm.seq" :min="1" :max="1000" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>

                <div class="dialog-footer flex right justify-end">
                  <el-button type="primary" @click="saveProject('projectFormRef')">保存</el-button>
                  <el-button @click="closeProjectDialog('projectFormRef')">取消</el-button>
                </div>
              </el-dialog>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';
import { AppStore } from '@/stores/store'; //'../../../stores/store';
let store = AppStore();

// 全局变量定义区 ==========
// 根据质控规则的关键字查询
let searchForm = {
  searchValue: ''
};
let showStandardDialog = ref(false); //中间字段弹框
let showProjectDialog = ref(false);
let tloading = ref(false); //加载状态
let ploading = ref(false); //加载状态
let projectList: any = reactive([]);
let standardList: any = reactive([]);
let sltStandard: any = ref({});
let activeName = ref('first');

let typeList = [
  { code: 'radio', name: '单选' },
  { code: 'check', name: '多选' },
  { code: 'num', name: '数字' },
  { code: 'txt', name: '文本' }
];

// 右侧基本信息表单
let standardForm = reactive({
  id: null,
  standardCode: '',
  standardName: '',
  standardType: '',
  purpose: '',
  remark: '',
  tool: '',
  seq: 1
});

let standardFormRule = {
  standardName: [
    {
      required: true,
      message: '请输入标准名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

let projectForm = reactive({
  id: null,
  standardId: '',
  projectCode: '',
  projectName: '',
  projectType: '',
  normalValue: '',
  exceptValue: '',
  defValue: '',
  maxValue: '',
  mixValue: '',
  range: '',
  seq: 1
});

let projectFormRule = {
  projectName: [
    {
      required: true,
      message: '请输入项目名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findPollingStandardList(); // 获取质控规则表格数据
});

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findPollingStandardList();
  }
}

function findPollingStandardList() {
  tloading.value = true;
  standardList.length = 0; //放入数据前清空数据
  const url = '/api/eq/eqPollingStandard/findPollingStandardList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue
      }
    })
    .then((res: any) => {
      standardList.push(...res.data);
      const kn = standardList.find((k) => k.id == sltStandard.value.id);
      if (isEmpty(kn)) {
        standardRowClick({ row: standardList[0] }); //默认选中第一条数据
      } else {
        standardRowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function findPollingProjectList() {
  ploading.value = true;
  projectList.length = 0; //放入数据前清空数据
  const url = '/api/eq/eqPollingProject/findPollingProjectList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        pid: sltStandard.value.id
      }
    })
    .then((res: any) => {
      projectList.push(...res.data);
      ploading.value = false;
    })
    .catch((err: any) => {
      ploading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

// 点击设计模式表格当前行触发右侧表单变化
function standardRowClick({ row }: any) {
  if (isEmpty(row)) {
    sltStandard.value = {};
  } else {
    (proxy.$refs.standardTableRef as any).setCurrentRow(row);
    sltStandard.value = row;
    findPollingProjectList();
  }
}

function addStandardDialog() {
  standardForm.seq = standardList.length + 1;
  showStandardDialog.value = true;
}

function addProjectDialog() {
  projectForm.standardId = sltStandard.value.id;
  projectForm.projectType = 'radio';
  projectForm.seq = projectList.length + 1;
  showProjectDialog.value = true;
}

function saveStandard(formName: any) {
  const el: any = proxy.$refs[formName];
  el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const obj = {
      id: standardForm.id,
      standardCode: standardForm.standardCode,
      standardName: standardForm.standardName,
      standardType: standardForm.standardType,
      purpose: standardForm.purpose,
      remark: standardForm.remark,
      tool: standardForm.tool,
      seq: standardForm.seq
    };
    let url = '';
    // 判断添加和编辑接口
    if (standardForm.id) {
      url = '/api/eq/eqPollingStandard/editPollingStandard';
    } else {
      url = '/api/eq/eqPollingStandard/addPollingStandard';
    }
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          if (standardForm.id) {
            VxeMessage('修改成功', VxeNotifyType.success);
          } else {
            VxeMessage('新增成功', VxeNotifyType.success);
          }
          showStandardDialog.value = false;
          sltStandard.value = res.data;
          findPollingStandardList();
          // 清空表单
          clearStandardForm();
        } else {
          if (standardForm.id) {
            VxeMessage('修改失败', VxeNotifyType.error);
          } else {
            VxeMessage('新增失败', VxeNotifyType.error);
          }
        }
      })
      .catch((err: any) => {
        VxeMessage('保存异常', VxeNotifyType.error);
      });
  });
}

function saveProject(formName: any) {
  const el: any = proxy.$refs[formName];
  el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const obj = {
      id: projectForm.id,
      standardId: projectForm.standardId,
      projectCode: projectForm.projectCode,
      projectName: projectForm.projectName,
      projectType: projectForm.projectType,
      normalValue: projectForm.normalValue,
      exceptValue: projectForm.exceptValue,
      defValue: projectForm.defValue,
      maxValue: projectForm.maxValue,
      mixValue: projectForm.mixValue,
      range: projectForm.range,
      seq: projectForm.seq
    };
    let url = '';
    // 判断添加和编辑接口
    if (projectForm.id) {
      url = '/api/eq/eqPollingProject/editPollingProject';
    } else {
      url = '/api/eq/eqPollingProject/addPollingProject';
    }
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          if (projectForm.id) {
            VxeMessage('修改成功', VxeNotifyType.success);
          } else {
            VxeMessage('新增成功', VxeNotifyType.success);
          }
          showProjectDialog.value = false;
          findPollingProjectList();
          // 清空表单
          clearProjectForm();
        } else {
          if (projectForm.id) {
            VxeMessage('修改失败', VxeNotifyType.error);
          } else {
            VxeMessage('新增失败', VxeNotifyType.error);
          }
        }
      })
      .catch((err: any) => {
        VxeMessage('保存异常', VxeNotifyType.error);
      });
  });
}

function deleteBatchStandard() {
  const sltSuppliers = (proxy.$refs.standardTableRef as any).getCheckboxRecords();
  if (!(sltSuppliers.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delPollingStandardList = sltSuppliers.filter((p: any) => !isEmpty(p.id));
        if (delPollingStandardList.length > 0) {
          const data = { pollingStandardList: delPollingStandardList };
          const url = '/api/eq/eqPollingStandard/batchDeletePollingStandardList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findPollingStandardList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function deleteBatchProject() {
  const sltSuppliers = (proxy.$refs.projectTableRef as any).getCheckboxRecords();
  if (!(sltSuppliers.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delPollingProjectList = sltSuppliers.filter((p: any) => !isEmpty(p.id));
        if (delPollingProjectList.length > 0) {
          const data = { pollingProjectList: delPollingProjectList };
          const url = '/api/eq/eqPollingProject/batchDeletePollingProjectList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findPollingProjectList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function closeStandardDialog(formMiddleName: any) {
  const el: any = proxy.$refs[formMiddleName];
  // 移除校验结果
  el.clearValidate();
  clearStandardForm();
  showStandardDialog.value = false;
}

function closeProjectDialog(formMiddleName: any) {
  const el: any = proxy.$refs[formMiddleName];
  // 移除校验结果
  el.clearValidate();
  clearProjectForm();
  showProjectDialog.value = false;
}

// 清空中间规则弹框表单
function clearStandardForm() {
  standardForm.id = null;
  standardForm.standardCode = '';
  standardForm.standardName = '';
  standardForm.standardType = '';
  standardForm.purpose = '';
  standardForm.remark = '';
  standardForm.tool = '';
  standardForm.seq = 1;
}

function clearProjectForm() {
  projectForm.id = null;
  projectForm.standardId = '';
  projectForm.projectCode = '';
  projectForm.projectName = '';
  projectForm.projectType = '';
  projectForm.normalValue = '';
  projectForm.exceptValue = '';
  projectForm.defValue = '';
  projectForm.maxValue = '';
  projectForm.mixValue = '';
  projectForm.range = '';
  projectForm.seq = 1;
}

// 编辑当前行规则
function editStandardDialog(row: any) {
  standardForm.id = row.id;
  standardForm.standardCode = row.standardCode;
  standardForm.standardName = row.standardName;
  standardForm.standardType = row.standardType;
  standardForm.purpose = row.purpose;
  standardForm.remark = row.remark;
  standardForm.tool = row.tool;
  standardForm.seq = row.seq;
  showStandardDialog.value = true;
}

function editProjectDialog(row: any) {
  projectForm.id = row.id;
  projectForm.standardId = row.standardId;
  projectForm.projectCode = row.projectCode;
  projectForm.projectName = row.projectName;
  projectForm.projectType = row.projectType;
  projectForm.normalValue = row.normalValue;
  projectForm.exceptValue = row.exceptValue;
  projectForm.defValue = row.defValue;
  projectForm.maxValue = row.maxValue;
  projectForm.mixValue = row.mixValue;
  projectForm.range = row.range;
  projectForm.seq = row.seq;
  showProjectDialog.value = true;
}

// 判断中间弹框显示的标题
function titleStandard() {
  if (standardForm.id) {
    return `编辑标准`;
  } else {
    return `新建标准`;
  }
}
function titleProject() {
  if (projectForm.id) {
    return `编辑项目`;
  } else {
    return `新建项目`;
  }
}

function formatProjectType(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
</script>

<style lang="scss" scoped>
#standardDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBody {
        height: calc(100% - 40px - 32px);
      }
      .el-tabs {
        height: 100%;
        :deep(.el-tabs__content) {
          height: calc(100% - 40px);
          padding: 0;
          .el-tab-pane {
            height: 100%;
          }
          #pane-first {
            padding: 15px;
          }
        }
      }
    }
  }
}
</style>

